#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/ide.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/gpio.h>
#include <linux/cdev.h>
#include <linux/device.h>
#include <linux/of.h>
#include <linux/of_address.h>
#include <linux/of_gpio.h>
// #include <asm/mach/map.h>
#include <asm/uaccess.h>
#include <asm/io.h>

#define DEVICE_CNT 1           // 设备号个数
#define NEW_LED_NAME "gpioled" // 设备名称




/*设备结构体*/
struct gpioled_dev
{
    dev_t devid;           // 设备号
    struct cdev cdev;      // 字符设备结构体
    struct class *class;   // 类
    struct device *device; // 设备
    int major;             // 主设备号
    int minor;             // 次设备号
    struct device_node *nd; /* 设备节点 */
    int led_gpio; /* led 所使用的 GPIO 编号 */
    int flag; /* 状态 */
    spinlock_t lock; //定义自旋锁
};

static struct gpioled_dev led_dev; // 设备结构体


static int led_open(struct inode *inode, struct file *filp)
{
    unsigned long flags;
    filp->private_data = &led_dev; // 设置私有数据

    spin_lock_irqsave(&led_dev.lock, flags); // 保护自旋锁
    if (led_dev.flag) // 判断设备已经打开
    {
        spin_unlock_irqrestore(&led_dev.lock, flags);
        printk("led is busy!\r\n");
        return -EBUSY;
    }
    led_dev.flag++; // 标记设备打开
    spin_unlock_irqrestore(&led_dev.lock, flags);
    printk("led open ok!\r\n");
    return 0;
}

static ssize_t led_read(struct file *filp, char __user *buf, size_t count, loff_t *pos)
{
    return 0;
}

static ssize_t led_write(struct file *filp, const char __user *buf, size_t count, loff_t *pos)
{
    int retvalue;
    unsigned char databuf[1];
    unsigned char ledstat;
    struct gpioled_dev *dev = filp->private_data;

    retvalue = copy_from_user(databuf, buf, count);
    if (retvalue < 0)
    {
        printk(KERN_INFO "kernel write failed!\r\n");
        return -EFAULT;
    }

    ledstat = databuf[0]; /* 获取状态值 */

    if (ledstat > 0)
    {
        gpio_set_value(dev->led_gpio,1); /* 打开 LED 灯 */
    }
    else
    {
        gpio_set_value(dev->led_gpio,0); /* 关闭 LED 灯 */
    }

    // 返回实际写入的字节数
    return 0;
}

static int led_release(struct inode *inode, struct file *filp)
{
    unsigned long flags;
    struct gpioled_dev *dev = filp->private_data;
    
    spin_lock_irqsave(&dev->lock,flags);
    if(dev->flag)
    {
        dev->flag--;
    }
    spin_unlock_irqrestore(&dev->lock,flags);

    printk("led release ok! flag = %d\r\n",dev->flag);
    return 0;
}

/* 设备操作函数 */
static struct file_operations led_fops = {
    .owner = THIS_MODULE,
    .open = led_open,
    .read = led_read,
    .write = led_write,
    .release = led_release,
};

/*
 * @description : 驱动出口函数
 * @param : 无
 * @return : 无
 */
static int __init led_init(void)
{
    int ret = -1;
    const char *str;

    //初始化锁
    spin_lock_init(&led_dev.lock);


    /* 设置LED使用的GPIO*/
    /*1. 获取设备树节点*/
    led_dev.nd = of_find_node_by_path("/gpio_led");
    if (led_dev.nd == NULL)
    {
        printk("<0>device tree node 'led' not find!\r\n");
        return -EINVAL;
    }
    /* 2. 读取status属性值*/
    ret = of_property_read_string(led_dev.nd, "status", &str);
    if (ret < 0)
    {
        printk("<0>read status property failed!\r\n");
        return -EINVAL;
    }
    
    if (strcmp(str, "okay")) // 判断状态  > 0 则返回失败
    {
        return -EINVAL;
    }
    /* 3. 获取compatible属性值并进行匹配 */
    ret = of_property_read_string(led_dev.nd, "compatible", &str);

    if (ret < 0)
    {
        printk("<0>read compatible property failed!\r\n");
        return -EINVAL;
    }

    if (strcmp(str, "alientek,led"))
    {
        printk("gpioled: Compatible match failed\r\n");
        return -EINVAL;
    }
    /* 4. 获取gpio属性值 得到LED 所使用的 GPIO 编号*/
    led_dev.led_gpio = of_get_named_gpio(led_dev.nd, "led-gpio", 0);
    if (led_dev.led_gpio < 0)
    {
        printk("<0>read led-gpios property failed!\r\n");
        return -EINVAL;
    }
    printk("led gpio num = %d\r\n", led_dev.led_gpio);

    /* 5. 向gpio子系统申请一个gpio*/
    ret = gpio_request(led_dev.led_gpio, "LED");
    if (ret < 0)
    {
        printk(KERN_ERR "<0>request led-gpios failed!\r\n");
        return ret;
    }

    /* 6. 设置gpio为输出模式并且输出低电平*/
    ret = gpio_direction_output(led_dev.led_gpio, 0);
    if (ret < 0)
    {
        printk(KERN_ERR "<0>set led-gpios failed!\r\n");
    }
    
    /* 7. 注册字符设备驱动 */
    if (led_dev.major)
    {
        led_dev.devid = MKDEV(led_dev.major, 0);
        ret = register_chrdev_region(led_dev.devid, DEVICE_CNT, NEW_LED_NAME);
        if (ret < 0)
        {
            pr_err("cannot register %s char driver [ret=%d]\n", 
                NEW_LED_NAME, DEVICE_CNT);
                goto free_gpio;  
        }
    }
    else
    {
        ret = alloc_chrdev_region(&led_dev.devid, 0, DEVICE_CNT, NEW_LED_NAME);
        if (ret < 0)
        {
            pr_err("%s Couldn't alloc_chrdev_region,ret=%d\r\n", 
                NEW_LED_NAME, ret);
            goto free_gpio;
        }
        led_dev.major = MAJOR(led_dev.devid);
        led_dev.minor = MINOR(led_dev.devid);
    }
    printk("major=%d, minor=%d\r\n", led_dev.major, led_dev.minor);
    // 创建字符设备
    led_dev.cdev.owner = THIS_MODULE;
    cdev_init(&led_dev.cdev, &led_fops);
    ret = cdev_add(&led_dev.cdev, led_dev.devid, DEVICE_CNT);
    if (ret < 0)
    {
        pr_err("cdev_add failed,ret=%d\r\n", ret);
        goto del_unregister;
    }
    /* 8. 创建类 */
    led_dev.class = class_create(THIS_MODULE, NEW_LED_NAME);
    if (IS_ERR(led_dev.class))
    {
        goto del_cdev;
    }
    /* 9. 创建设备 */
    led_dev.device = device_create(led_dev.class, NULL, led_dev.devid, NULL, NEW_LED_NAME);
    if (IS_ERR(led_dev.device))
    {
        goto destroy_class;
    }
    return 0;
destroy_class:
    class_destroy(led_dev.class);
del_cdev:
    cdev_del(&led_dev.cdev);
del_unregister:
    unregister_chrdev_region(led_dev.devid, DEVICE_CNT);
free_gpio:
    gpio_free(led_dev.led_gpio);
    return -EIO;
}

void __exit led_exit(void)
{

    cdev_del(&led_dev.cdev);
    unregister_chrdev(DEVICE_CNT, NEW_LED_NAME);
    device_destroy(led_dev.class, led_dev.devid);/* 注销设备 */
    class_destroy(led_dev.class);/* 注销类 */
    gpio_free(led_dev.led_gpio);/* 释放 GPIO */
    printk("led exit ok!\r\n");
}

module_init(led_init);
module_exit(led_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("JACK");
MODULE_INFO(intree, "Y");
